package jp.shuitic.hatebwebhook.twitter.handler;


import jp.shuitic.hatebwebhook.twitter.web.client.HatebWebHookTwitUser;
import jp.shuitic.hatebwebhook.twitter.web.server.HatebWebHookTwitUserService;
import jp.shuitic.hatebwebhook.twitter.web.server.HatebWebHookTwitUserServiceImpl;

/**
 * はてブのユーザをチェックする実装
 * @author shuitic
 */
public class HatebHookCheckerImpl implements HatebHookChecker {

	static private HatebWebHookTwitUserService hwtUserService;
	static {
		hwtUserService = new HatebWebHookTwitUserServiceImpl();
	}
	

	@Override
	public boolean checkKey(String username, String key, String url,
			String title, String status, String timestamp, String comment,
			String isPrivate) throws Exception {

		if (isEmpty(username) || isEmpty(key) || isEmpty(url) || 
				(isEmpty(title) && isEmpty(comment)) || 
				(isEmpty(status) || !status.equals("add")) || 
				"1".equals(isPrivate)) {
			//パラメータが対象外の場合
			return false;
		}
		
		if (isTooLong(username) || isTooLong(key) || isTooLong(url) || isTooLong(title) || isTooLong(status) || isTooLong(comment)) {
			return false;
		}

		HatebWebHookTwitUser hwtUser =  hwtUserService.findByHatebUserName(username);
		return (hwtUser != null) && hwtUser.getHatebWebHookKey().equals(key) && hwtUser.isEnable();
	}
	/**
	 * 文字列がnullか空の場合Trueを返す
	 * @param value
	 * @return
	 */
	private static boolean isEmpty(String value) {
		return ((value == null) || (value.equals("")));
	}
	
	/**
	 * 文字列の長さが255バイト以上の場合はtrueを返す
	 * @param value
	 * @return
	 */
	private static boolean isTooLong(String value) {
		if (isEmpty(value)) {
			return false;
		}
		if (value.getBytes().length > 255) {
			return true;
		} else {
			return false;
		}
	}

}
